<?php
/**
 * Description: 获取支付宝app支付需要的参数
 * User: devforma
 * Date: 15/11/16
 * Time: 16:38
 */

require CONFIG_DIR . '/pay.config.php';

class GetAlipayParams implements iController {

    private static $privateKeyPath;
    private $terminalType = '';
    private $appType = '';

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {

        if (validateUser($queryArgs) !== 1 || !isset($queryArgs['order_id'])
            || !filter_var($queryArgs['order_id'], FILTER_VALIDATE_INT) || empty($queryArgs['terminal_type'])) {
            return genOutput(1000);
        }

        $this->terminalType = empty($queryArgs['terminal_type']) ? '' : $queryArgs['terminal_type'];
        $this->appType = empty($queryArgs['app_type']) ? '' : $queryArgs['app_type'];
        self::$privateKeyPath  = CONFIG_DIR . '/keyfiles/appub_rsa_private_key.pem';

        if ($orderInfo = $this->getOrderInfo($queryArgs['order_id'], $queryArgs['user_id'])) {
            $paramStr = $this->genParamStr($orderInfo);

            return genOutput(1, array(
                'param_str' => $paramStr
            ));

        }

        return genOutput(1001);
    }

    /**
     * 校验订单的有效性,并更新app类型
     *
     * @param $orderId
     * @param $userId
     * @return bool
     */
    private function getOrderInfo($orderId, $userId) {
        global $cmsdb;

        $exists = getOrderInfo($orderId, $userId);

        if ($exists) {
            $cmsdb->update('original_orders', array('app_type' => $this->appType), array('order_id' => $orderId));
            return $exists;
        }

        return false;
    }

    /**
     * 生成参数字符串
     *
     * @param $orderInfo
     * @return string
     */
    private function genParamStr($orderInfo) {
        $productInfo = $this->getProductInfo($orderInfo->product_id, $orderInfo->product_type);
        if ($this->terminalType === 'iOS_phone') {
            $params = array(
                'partner='        . self::addQuote(ALIPAY_PARTNER),
                'seller_id='      . self::addQuote(ALIPAY_SELLER),
                'subject='        . self::addQuote($productInfo['name']),
                'body='           . self::addQuote($productInfo['name']),
                'total_fee='      . self::addQuote($orderInfo->price),
                'notify_url='     . self::addQuote(ALIPAY_MOBILE_NOTIFY_URL),
                'service='        . self::addQuote('mobile.securitypay.pay'),
                'it_b_pay='       . self::addQuote($productInfo['valid_pay_period'] . 'm'),
                'out_trade_no='   . self::addQuote($orderInfo->order_id),
            );
        } else {
            $params = array(
                'partner='        . self::addQuote(ALIPAY_PARTNER),
                'subject='        . self::addQuote($productInfo['name']),
                'body='           . self::addQuote($productInfo['name']),
                'total_fee='      . self::addQuote($orderInfo->price),
                'notify_url='     . self::addQuote(urlencode(ALIPAY_MOBILE_NOTIFY_URL)),
                'service='        . self::addQuote('mobile.securitypay.pay'),
                '_input_charset=' . self::addQuote('utf-8'),
                'return_url='     . self::addQuote(urlencode('http://m.alipay.com')),
                'payment_type='   . self::addQuote(1),
                'seller_id='      . self::addQuote(ALIPAY_SELLER),
                'it_b_pay='       . self::addQuote($productInfo['valid_pay_period'] . 'm'),
                'out_trade_no='   . self::addQuote($orderInfo->order_id)
            );
        }

        //生成rsa签名字符串
        $paramStr = implode('&', $params);
        $sign = $this->rsaSign($paramStr, self::$privateKeyPath);

        array_pop($params);
        $extraParams = array(
            'sign='         . self::addQuote(urlencode($sign)),
            'sign_type='    . self::addQuote('RSA'),
            'out_trade_no=' . self::addQuote($orderInfo->order_id)
        );

        return implode('&', array_merge($params, $extraParams));
    }

    /**
     * 字符串两边增加双引号
     *
     * @param $str
     * @return string
     */
    private static function addQuote($str) {
        return '"' . $str . '"';
    }

    /**
     * 获取商品信息
     *
     * @param $productId
     * @param $productType
     * @return array
     */
    private function getProductInfo($productId, $productType) {
        global $cmsdb;

        $info = array('name' => '', 'valid_pay_period' => 30);

        switch ($productType) {
            case 'zhiboke':
                $data = getOrderCourseInfo($productId);

                $info['name'] = $data->course_name;
                if ($data->valid_pay_period)
                    $info['valid_pay_period'] = $data->valid_pay_period;

                break;

            case 'course':
                $sql = 'SELECT `course_name` FROM `data_vod_course` WHERE `id`=:id';
                $info['name'] = $cmsdb->getVar($sql, array(':id' => $productId));

                break;

            case 'interview':
                $sql = 'SELECT `product_name` FROM `conf_product` WHERE `id`=:id';
                $info['name'] = $cmsdb->getVar($sql, array(':id' => $productId));

                break;

            default:
                break;
        }

        $info['name'] = str_replace('+', '和', $info['name']);

        return $info;
    }

    /**
     * RSA签名
     *
     * @param string $data 待签名数据
     * @param string $privateKeyPath 支付宝的公]私钥文件路径
     * @return string
     */
    private function rsaSign($data, $privateKeyPath) {
        $priKey = file_get_contents($privateKeyPath);
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);

        return base64_encode($sign);
    }
}